<template>
  <div class="sales-analytics">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 登录提示 -->
      <div v-if="!isLoggedIn" class="login-prompt">
        <div class="login-prompt-icon">📊</div>
        <h3>请先登录</h3>
        <p>您需要登录商家账户才能查看销售分析数据</p>
        <div class="login-prompt-actions">
          <button class="btn-primary" @click="goToLogin">商家登录</button>
          <button class="btn-cancel" @click="goToRegister">注册商家</button>
        </div>
      </div>

      <div v-if="isLoggedIn" class="content-header">
        <h1>销售分析</h1>
        <p>查看您的销售数据和趋势分析</p>
      </div>
      
      <template v-if="isLoggedIn">
        <!-- 年月选择器 -->
        <div class="date-selector">
        <div class="selector-group">
          <label>年份:</label>
          <select v-model="selectedYear" @change="onYearChange">
            <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
          </select>
        </div>
        <div class="selector-group">
          <label>月份:</label>
          <select v-model="selectedMonth" @change="onMonthChange">
            <option v-for="month in months" :key="month.value" :value="month.value">{{ month.label }}</option>
          </select>
        </div>
        <button class="refresh-btn" @click="refreshData" :disabled="loading">
          <i class="icon">🔄</i>
          {{ loading ? '加载中...' : '刷新数据' }}
        </button>
        <button class="export-btn" @click="exportToExcel" :disabled="loading">
          <i class="icon">导出</i>
          导出为 Excel
        </button>
      </div>
      
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stats-card">
          <div class="stats-icon">💰</div>
          <div class="stats-content">
            <div class="stats-value">¥{{ formatNumber(monthlyStats.totalIncome) }}</div>
            <div class="stats-label">本月总收入</div>
          </div>
        </div>
        
        <div class="stats-card">
          <div class="stats-icon">📋</div>
          <div class="stats-content">
            <div class="stats-value">{{ formatNumber(monthlyStats.totalOrders) }}</div>
            <div class="stats-label">本月总单数</div>
          </div>
        </div>
        
        <div class="stats-card">
          <div class="stats-icon">📦</div>
          <div class="stats-content">
            <div class="stats-value">{{ formatNumber(monthlyStats.totalQuantity) }}</div>
            <div class="stats-label">本月总销售数量</div>
          </div>
        </div>
        
        <div class="stats-card">
          <div class="stats-icon">📈</div>
          <div class="stats-content">
            <div class="stats-value">¥{{ formatNumber(yearlyStats.totalIncome) }}</div>
            <div class="stats-label">年收入</div>
          </div>
        </div>
      </div>
      
      <!-- ECharts图表容器 -->
      <div class="charts-container">
        <!-- 日销售数据图表 -->
        <div class="chart-section">
          <h3>{{ selectedYear }}年{{ selectedMonth }}月 - 日销售数据</h3>
          <div class="chart-wrapper">
            <div ref="dailyChart" class="echarts-container"></div>
          </div>
        </div>
        
        <!-- 月销售数据图表 -->
        <div class="chart-section">
          <h3>{{ selectedYear }}年 - 月销售数据</h3>
          <div class="chart-wrapper">
            <div ref="monthlyChart" class="echarts-container"></div>
          </div>
        </div>
      </div>
      </template>
    </div>
  </div>
</template>

<script>
import { queryDailySales, queryMonthlySales } from '@/api/seller'
import * as echarts from 'echarts'

export default {
  name: 'SalesAnalytics',
  computed: {
    // 检查商家登录状态
    isLoggedIn() {
      return !!localStorage.getItem('sellerId')
    }
  },
  data() {
    return {
      selectedYear: new Date().getFullYear(),
      selectedMonth: new Date().getMonth() + 1,
      years: [],
      months: [
        { value: 1, label: '1月' },
        { value: 2, label: '2月' },
        { value: 3, label: '3月' },
        { value: 4, label: '4月' },
        { value: 5, label: '5月' },
        { value: 6, label: '6月' },
        { value: 7, label: '7月' },
        { value: 8, label: '8月' },
        { value: 9, label: '9月' },
        { value: 10, label: '10月' },
        { value: 11, label: '11月' },
        { value: 12, label: '12月' }
      ],
      dailySalesData: [],
      monthlySalesData: [],
      sellerId: null,
      loading: false,
      dailyChart: null,
      monthlyChart: null,
      // 统计数据
      monthlyStats: {
        totalIncome: 0,
        totalOrders: 0,
        totalQuantity: 0
      },
      yearlyStats: {
        totalIncome: 0
      }
    }
  },
  mounted() {
    // 只在登录状态下才初始化和加载数据
    if (this.isLoggedIn) {
      this.initializeData()
      this.loadData()
    }
  },
  
  beforeUnmount() {
    if (this.dailyChart) {
      this.dailyChart.dispose()
    }
    if (this.monthlyChart) {
      this.monthlyChart.dispose()
    }
  },
  methods: {
    initializeData() {
      // 初始化年份选项（最近5年）
      const currentYear = new Date().getFullYear()
      for (let i = currentYear - 4; i <= currentYear; i++) {
        this.years.push(i)
      }
      
      // 获取商家ID
      this.sellerId = localStorage.getItem('sellerId')
      if (!this.sellerId) {
        console.error('未找到商家ID，请先登录')
        return
      }
    },
    
    async loadData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadDailySales(),
          this.loadMonthlySales()
        ])
        this.renderCharts()
      } catch (error) {
        console.error('加载数据失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    async loadDailySales() {
      try {
        const response = await queryDailySales(this.sellerId, this.selectedYear, this.selectedMonth)
        console.log('日销售数据响应:', response)
        // 处理API响应数据格式
        if (Array.isArray(response)) {
          this.dailySalesData = response
        } else if (response && response.data) {
          this.dailySalesData = response.data
        } else if (response && Array.isArray(response.result)) {
          this.dailySalesData = response.result
        } else {
          this.dailySalesData = []
        }
        console.log('处理后的日销售数据:', this.dailySalesData)
        // 计算本月统计数据
        this.calculateMonthlyStats()
      } catch (error) {
        console.error('加载日销售数据失败:', error)
        this.dailySalesData = []
        this.calculateMonthlyStats()
      }
    },
    
    async loadMonthlySales() {
      try {
        const response = await queryMonthlySales(this.sellerId, this.selectedYear)
        console.log('月销售数据响应:', response)
        // 处理API响应数据格式
        if (Array.isArray(response)) {
          this.monthlySalesData = response
        } else if (response && response.data) {
          this.monthlySalesData = response.data
        } else if (response && Array.isArray(response.result)) {
          this.monthlySalesData = response.result
        } else {
          this.monthlySalesData = []
        }
        console.log('处理后的月销售数据:', this.monthlySalesData)
        // 计算年度统计数据
        this.calculateYearlyStats()
      } catch (error) {
        console.error('加载月销售数据失败:', error)
        this.monthlySalesData = []
        this.calculateYearlyStats()
      }
    },
    
    renderCharts() {
      this.$nextTick(() => {
        this.initDailyChart()
        this.initMonthlyChart()
      })
    },
    
    initDailyChart() {
      if (this.dailyChart) {
        this.dailyChart.dispose()
      }
      const chartDom = this.$refs.dailyChart
      if (!chartDom) return
      
      this.dailyChart = echarts.init(chartDom)
      this.renderDailyChart()
    },
    
    initMonthlyChart() {
      if (this.monthlyChart) {
        this.monthlyChart.dispose()
      }
      const chartDom = this.$refs.monthlyChart
      if (!chartDom) return
      
      this.monthlyChart = echarts.init(chartDom)
      this.renderMonthlyChart()
    },
    
    renderDailyChart() {
      if (!this.dailyChart) return
      
      console.log('准备绘制日销售图表，数据长度:', this.dailySalesData.length)
      console.log('日销售数据:', this.dailySalesData)
      
      if (this.dailySalesData.length === 0) {
        this.dailyChart.setOption({
          title: {
            text: `${this.selectedYear}年${this.selectedMonth}月 - 日销售数据`,
            left: 'center',
            textStyle: { fontSize: 16 }
          },
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无日销售数据',
              fontSize: 14,
              fill: '#999'
            }
          }
        })
        return
      }
      
      // 准备数据
      const data = this.dailySalesData.map(item => {
        const dateObj = new Date(item.saleDate)
        return {
          date: dateObj.getDate(),
          income: parseFloat(item.dailyIncome) || 0,
          quantity: parseInt(item.dailyQuantity) || 0,
          orders: parseInt(item.orderCount) || 0,
          fullDate: item.saleDate
        }
      }).sort((a, b) => a.date - b.date)
      
      console.log('处理后的日销售数据:', data)
      
      const dates = data.map(item => `${item.date}日`)
      const incomeData = data.map(item => item.income)
      const quantityData = data.map(item => item.quantity)
      const ordersData = data.map(item => item.orders)
      
      const option = {
        title: {
          text: `${this.selectedYear}年${this.selectedMonth}月 - 日销售数据`,
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        legend: {
          data: ['销售金额', '销售数量', '订单数量'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          boundaryGap: false
        },
        yAxis: [
          {
            type: 'value',
            name: '金额(元)',
            position: 'left',
            axisLabel: { formatter: '{value}' }
          },
          {
            type: 'value',
            name: '数量',
            position: 'right',
            axisLabel: { formatter: '{value}' }
          }
        ],
        series: [
          {
            name: '销售金额',
            type: 'line',
            yAxisIndex: 0,
            data: incomeData,
            smooth: true,
            lineStyle: { color: '#5470c6', width: 2 },
            itemStyle: { color: '#5470c6' },
            areaStyle: { opacity: 0.1 }
          },
          {
            name: '销售数量',
            type: 'line',
            yAxisIndex: 1,
            data: quantityData,
            smooth: true,
            lineStyle: { color: '#91cc75', width: 2 },
            itemStyle: { color: '#91cc75' }
          },
          {
            name: '订单数量',
            type: 'line',
            yAxisIndex: 1,
            data: ordersData,
            smooth: true,
            lineStyle: { color: '#fac858', width: 2 },
            itemStyle: { color: '#fac858' }
          }
        ]
      }
      
      this.dailyChart.setOption(option)
    },
    
    renderMonthlyChart() {
      if (!this.monthlyChart) return
      
      if (this.monthlySalesData.length === 0) {
        this.monthlyChart.setOption({
          title: {
            text: `${this.selectedYear}年 - 月销售数据`,
            left: 'center',
            textStyle: { fontSize: 16 }
          },
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无月销售数据',
              fontSize: 14,
              fill: '#999'
            }
          }
        })
        return
      }
      
      // 准备数据
      const monthMap = {
        'JANUARY': 1, 'FEBRUARY': 2, 'MARCH': 3, 'APRIL': 4,
        'MAY': 5, 'JUNE': 6, 'JULY': 7, 'AUGUST': 8,
        'SEPTEMBER': 9, 'OCTOBER': 10, 'NOVEMBER': 11, 'DECEMBER': 12
      }
      
      const data = this.monthlySalesData.map(item => ({
        month: monthMap[item.salesmonth] || 1,
        income: parseFloat(item.totalIncome) || 0,
        quantity: parseInt(item.totalQuantity) || 0,
        orders: parseInt(item.totalOrderCount) || 0
      })).sort((a, b) => a.month - b.month)
      
      const months = data.map(item => `${item.month}月`)
      const incomeData = data.map(item => item.income)
      const quantityData = data.map(item => item.quantity)
      const ordersData = data.map(item => item.orders)
      
      const option = {
        title: {
          text: `${this.selectedYear}年 - 月销售数据`,
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        legend: {
          data: ['销售金额', '销售数量', '订单数量'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months,
          boundaryGap: false
        },
        yAxis: [
          {
            type: 'value',
            name: '金额(元)',
            position: 'left',
            axisLabel: { formatter: '{value}' }
          },
          {
            type: 'value',
            name: '数量',
            position: 'right',
            axisLabel: { formatter: '{value}' }
          }
        ],
        series: [
          {
            name: '销售金额',
            type: 'line',
            yAxisIndex: 0,
            data: incomeData,
            smooth: true,
            lineStyle: { color: '#5470c6', width: 2 },
            itemStyle: { color: '#5470c6' },
            areaStyle: { opacity: 0.1 }
          },
          {
            name: '销售数量',
            type: 'line',
            yAxisIndex: 1,
            data: quantityData,
            smooth: true,
            lineStyle: { color: '#91cc75', width: 2 },
            itemStyle: { color: '#91cc75' }
          },
          {
            name: '订单数量',
            type: 'line',
            yAxisIndex: 1,
            data: ordersData,
            smooth: true,
            lineStyle: { color: '#fac858', width: 2 },
            itemStyle: { color: '#fac858' }
          }
        ]
      }
      
      this.monthlyChart.setOption(option)
    },
    

    
    async onYearChange() {
      await this.loadData()
    },
    
    async onMonthChange() {
      this.loading = true
      try {
        await this.loadDailySales()
        this.renderDailyChart()
      } catch (error) {
        console.error('切换月份失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    async refreshData() {
      await this.loadData()
    },
    
    // 计算本月统计数据
    calculateMonthlyStats() {
      if (!this.dailySalesData || this.dailySalesData.length === 0) {
        this.monthlyStats = {
          totalIncome: 0,
          totalOrders: 0,
          totalQuantity: 0
        }
        return
      }
      
      const stats = this.dailySalesData.reduce((acc, item) => {
        acc.totalIncome += parseFloat(item.dailyIncome) || 0
        acc.totalOrders += parseInt(item.orderCount) || 0
        acc.totalQuantity += parseInt(item.dailyQuantity) || 0
        return acc
      }, { totalIncome: 0, totalOrders: 0, totalQuantity: 0 })
      
      this.monthlyStats = stats
    },
    
    // 计算年度统计数据
    calculateYearlyStats() {
      if (!this.monthlySalesData || this.monthlySalesData.length === 0) {
        this.yearlyStats = {
          totalIncome: 0
        }
        return
      }
      
      const totalIncome = this.monthlySalesData.reduce((acc, item) => {
        return acc + (parseFloat(item.totalIncome) || 0)
      }, 0)
      
      this.yearlyStats = {
        totalIncome: totalIncome
      }
    },
    
    // 格式化数字显示
    formatNumber(num) {
      if (num === null || num === undefined || isNaN(num)) {
        return '0'
      }
      
      const number = parseFloat(num)
      
      if (number >= 10000) {
        return (number / 10000).toFixed(1) + '万'
      } else if (number >= 1000) {
        return (number / 1000).toFixed(1) + 'k'
      } else {
        return number.toLocaleString()
      }
    },

    // 跳转到商家登录页面
    goToLogin() {
      this.$router.push('/seller-login')
    },

    // 跳转到商家注册页面
    goToRegister() {
      this.$router.push('/seller-login') // 商家注册通常在登录页面
    },

    // 导出数据到 Excel
    exportToExcel() {
      import('xlsx').then(XLSX => {
        // 整理日销售数据
        const dailyData = this.dailySalesData.map(item => ({
          '日期': item.saleDate,
          '销售金额(元)': item.dailyIncome,
          '销售数量': item.dailyQuantity,
          '订单数量': item.orderCount
        }))

        // 整理月销售数据
        const monthlyData = this.monthlySalesData.map(item => ({
          '月份': item.salesmonth,
          '销售金额(元)': item.totalIncome,
          '销售数量': item.totalQuantity,
          '订单数量': item.totalOrderCount
        }))

        // 创建工作簿
        const wb = XLSX.utils.book_new()
        wb.SheetNames.push('日销售数据', '月销售数据')

        // 添加工作表
        wb.Sheets['日销售数据'] = XLSX.utils.json_to_sheet(dailyData)
        wb.Sheets['月销售数据'] = XLSX.utils.json_to_sheet(monthlyData)

        // 生成并下载文件
        XLSX.writeFile(wb, `销售分析_${this.selectedYear}年${this.selectedMonth}月.xlsx`)
      }).catch(error => {
        console.error('导出失败:', error)
        this.$message.error('导出失败，请检查依赖是否安装')
      })
    }
  }
}
</script>

<style scoped>
.sales-analytics {
  padding: 0;
}

.main-content {
  max-height: 100vh;
  min-height: 100vh;
  padding: 30px;
  overflow-y: auto;
}

.content-header {
  margin-bottom: 30px;
}

.content-header h1 {
  font-size: 28px;
  color: #333;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.content-header p {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.date-selector {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.selector-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selector-group label {
  font-weight: 500;
  color: #333;
  min-width: 50px;
}

.selector-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.selector-group select:hover {
  border-color: #667eea;
}

.selector-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.refresh-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.refresh-btn .icon {
  font-size: 16px;
}

.export-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%); /* 绿色系 */
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.export-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.export-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.export-btn .icon {
  font-size: 16px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stats-card {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 20px;
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stats-card:nth-child(1) {
  border-left-color: #4CAF50;
}

.stats-card:nth-child(2) {
  border-left-color: #2196F3;
}

.stats-card:nth-child(3) {
  border-left-color: #FF9800;
}

.stats-card:nth-child(4) {
  border-left-color: #9C27B0;
}

.stats-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.stats-content {
  flex: 1;
}

.stats-value {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 5px;
  line-height: 1.2;
}

.stats-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.chart-section {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chart-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

.chart-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.echarts-container {
  width: 100%;
  height: 400px;
  border: 1px solid #eee;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    margin-left: 200px;
    padding: 20px;
  }
  
  .date-selector {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .stats-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
  }
  
  .echarts-container {
    width: 100%;
    max-width: 700px;
    height: 350px;
  }
}

/* 登录提示样式 */
.login-prompt {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  margin: 40px auto;
}

.login-prompt-icon {
  font-size: 64px;
  color: #409eff;
  margin-bottom: 20px;
}

.login-prompt h3 {
  color: #333;
  font-size: 24px;
  margin-bottom: 12px;
  font-weight: 600;
}

.login-prompt p {
  color: #666;
  font-size: 16px;
  margin-bottom: 30px;
  line-height: 1.5;
}

.login-prompt-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.login-prompt-actions button {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 6px;
  min-width: 120px;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-cancel {
  background-color: #909399;
  color: white;
}

.btn-cancel:hover {
  background-color: #a6a9ad;
}

@media (max-width: 768px) {
  .main-content {
    margin-left: 0;
    padding: 15px;
  }
  
  .content-header h1 {
    font-size: 24px;
  }
  
  .date-selector {
    flex-direction: column;
    align-items: stretch;
  }
  
  .selector-group {
    justify-content: space-between;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .stats-card {
    padding: 20px;
  }
  
  .stats-icon {
    font-size: 28px;
    width: 50px;
    height: 50px;
  }
  
  .stats-value {
    font-size: 20px;
  }
  
  .echarts-container {
    width: 100%;
    max-width: 500px;
    height: 300px;
  }
}
</style>